package datastructures.stack;

/**
 * 链表实现栈
 *
 * @author hck
 */
@SuppressWarnings("Duplicates")
public class LinkedStack<T> {
    /**
     * 头节点
     */
    private Node top;

    private Node tail;

    private int size = 0;

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void push(T data) {
        Node last = tail;
        Node fresh = new Node(last, data, null);
        tail = fresh;
        if (top == null) {
            top = fresh;
        } else {
            last.next = fresh;
        }
        size++;
    }

    public T pop() {
        if (size == 0) {
            return null;
        }
        Node last = tail;
        tail = last.prefix;
        if (tail != null) {
            tail.next = null;
        } else {
            tail = top;
        }
        size--;
        return last.data;
    }

    public T peek() {
        if (size == 0) {
            return null;
        }
        return tail.data;
    }

    public void print() {
        if (size == 0) {
            System.out.println("[]");
        }
        System.out.print("[");
        Node cursor = top;
        for (int i = 0; i < size; i++) {
            System.out.print(cursor.data);
            if (i != size - 1) {
                System.out.print(",");
            }
            cursor = cursor.next;
        }
        System.out.println("]");
    }

    private class Node {
        T data;
        Node prefix;
        Node next;

        private Node(Node prefix, T data, Node next) {
            this.prefix = prefix;
            this.data = data;
            this.next = next;
        }
    }
}
